package me.zhengjie.modules.blog.rest;

import me.zhengjie.aop.log.Log;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.blog.domain.BlogUser;
import me.zhengjie.modules.blog.service.BlogUserService;
import me.zhengjie.modules.blog.service.dto.BlogUserDTO;
import me.zhengjie.modules.blog.service.query.BlogUserQueryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import static org.hibernate.id.IdentifierGenerator.ENTITY_NAME;

/**
 * @author zhangqiang
 * @date 2019-03-01
 */
@RestController
@RequestMapping("api")
public class BlogUserController {

    @Autowired
    private BlogUserQueryService blogUserQueryService;
    @Autowired
    private BlogUserService blogUserService;

    @Log("查询用户")
    @GetMapping(value = "/blogUsers")
    @PreAuthorize("hasAnyRole('ADMIN','USER_ALL','USER_SELECT')")
    public ResponseEntity getUsers(BlogUserDTO userDTO, Pageable pageable){
        return new ResponseEntity(blogUserQueryService.queryAll(userDTO,pageable), HttpStatus.OK);
    }


    @Log("新增用户")
    @PostMapping(value = "/blogUsers")
    @PreAuthorize("hasAnyRole('ADMIN','USER_ALL','USER_CREATE')")
    public ResponseEntity create(@Validated @RequestBody BlogUser resources){
        if (resources.getId() != null) {
            throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID");
        }
        return new ResponseEntity(blogUserService.create(resources),HttpStatus.CREATED);
    }

    @Log("修改用户")
    @PutMapping(value = "/blogUsers")
    @PreAuthorize("hasAnyRole('ADMIN','USER_ALL','USER_EDIT')")
    public ResponseEntity update(@Validated(BlogUser.Update.class) @RequestBody BlogUser resources){
        blogUserService.update(resources);
        return new ResponseEntity(HttpStatus.NO_CONTENT);
    }

    @Log("删除用户")
    @DeleteMapping(value = "/blogUsers/{id}")
    @PreAuthorize("hasAnyRole('ADMIN','USER_ALL','USER_DELETE')")
    public ResponseEntity delete(@PathVariable Long id){
        blogUserService.delete(id);
        return new ResponseEntity(HttpStatus.OK);
    }

}
